package com.dlc.apk

import com.danikula.videocache.HttpProxyCacheServer
import com.dlc.apk.core.DeviceManager
import com.dlc.apk.base.BaseApp
import com.dlc.apk.core.*
import com.dlc.apk.utils.DeviceUtil
import com.dlc.apk.utils.LogPlus
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import java.io.File

class App : BaseApp() {
    override fun init() {
        super.init()
        instance = this
        //log
        initLog()
        //串口初始化打开
        initSerialPort()
        //设备使用流程管理
        initDeviceManager()
        //MQTT client
        MQTTClient.init()
        //语音
        VoiceManager.getInstance().init(this)
    }

    private fun initSerialPort() {
        DeviceSerialManager.instance.init()
    }

    private fun initLog() {
        val logFileName = DeviceUtil.packageName
        LogPlus.setSaveLogToFile(true, logFileName)
        LogPlus.e("###当前app版本号 -> ${DeviceUtil.packageVersion}")
    }

    private fun initDeviceManager() {
        DeviceManager.instance.init(HardwareControllerImpl(), ReportListener())
    }

    override fun onTerminate() {
        super.onTerminate()
        MQTTClient.release()
    }

    private var mProxy: HttpProxyCacheServer? = null
    fun getVideoCacheProxy(): HttpProxyCacheServer {
        return if (mProxy == null) newProxy().also { mProxy = it } else mProxy!!
    }

    private fun newProxy(): HttpProxyCacheServer {
        return HttpProxyCacheServer.Builder(this)
            .cacheDirectory(File(externalCacheDir, "video-cache")).build()
    }

    init {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.whiteEEE, android.R.color.white) //全局设置主题颜色
            MaterialHeader(context) //.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //指定为经典Footer，默认是 BallPulseFooter
            ClassicsFooter(context).setDrawableSize(20f)
        }
    }

    companion object {
        lateinit var instance: App
            private set
    }
}